package cn.example.vip.mall.filter;

import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器，解决跨域问题
 */
@CrossOrigin
@WebFilter(urlPatterns = "/**")
public class CORSFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
	}
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
		httpResponse.setHeader("Access-Control-Allow-Headers", "*");
		httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
		httpResponse.setHeader("Access-Control-Max-Age", "3600");
		httpResponse.setHeader("Access-Control-Expose-Headers", "*");
		System.out.println("****************** CORS Configuration Completed *******************");
//		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//		if (httpServletRequest.getMethod().equals("OPTIONS")) {
//			httpResponse.setStatus(HttpServletResponse.SC_OK);
//		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
	
	@Override
	public void destroy() {
		Filter.super.destroy();
	}
	
}
